<template>
  <d2-container>
    <template slot="header">
      <el-button size="small" type="plain" @click="uploadDialogVisible=true">数据上传</el-button>
    </template>
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="养殖池">
       <el-select size="small" v-model="searchForm.culturePondId" placeholder="请选择养殖池">
          <el-option v-for="culturePond in culturePonds" :key="culturePond.id" :label="culturePond.id + ':' + culturePond.cpName" :value="culturePond.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据类型">
       <el-select size="small" v-model="searchForm.dataType" placeholder="请选择数据类型">
        <el-option label="WATER_TEMP:水温" value="WATER_TEMP"></el-option>
        <el-option label="PH:PH值" value="PH"></el-option>
        <el-option label="SALINITY:盐度" value="SALINITY"></el-option>
        <el-option label="DISSOLVED_OXYGEN:溶氧" value="DISSOLVED_OXYGEN"></el-option>
        <el-option label="AMMONIA:氨氮" value="AMMONIA"></el-option>
        <el-option label="COD:COD" value="COD"></el-option>
       </el-select>
      </el-form-item>
      <el-form-item label="监控日期">   
        <el-date-picker
         :clearable="false"
          v-model="searchForm.date"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="tagList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="tableLoading" :data="tags" style="width: 100%;" :stripe="true" :border="true">
      <el-table-column prop="monitorDataId" label="数据ID">
      </el-table-column>
      <el-table-column prop="value" label="监控数值">
      </el-table-column>
      <el-table-column prop="monitorTime" label="监控时间">
      </el-table-column>
      <el-table-column prop="action" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="showDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteTag(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog v-loading="uploadDialogLoading" title="数据上传" :visible.sync="uploadDialogVisible">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="baseUrl + '/monitorData/upload'"
        :on-remove="handleRemove"
        :limit="1"
        :headers="{'Authorization':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzY5NTM3ODcsInVzZXJJZCI6IjE0NTE4MzEyNzQ3MjAyNjQxOTQiLCJ1c2VybmFtZSI6ImFkbWluIn0.w_CDnTwfARyIDSuVZ0bB54pqn89R0shU9tkvEaUaOpg'}"
        accept="xlsx"
        :on-exceed="handleExceed"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        name="uploadFile"
        :file-list="uploadFileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      </el-upload>
      <!-- <el-form v-if="uploadDialogVisible" :model="fileForm" ref="editForm">
        <el-form-item label="文件上传" label-width="120px" prop="fileUuid">
          <el-input v-show="false" v-model="fileForm.fileUuid"></el-input>
          <el-upload class="upload-demo" :action="baseUrl + '/monitorData/upload'" headers="" :on-remove="handleRemove" :on-success="handleSuccess" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" :file-list="uploadFileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadExcel()">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog v-loading="editLoading" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form v-if="dialogVisible" :model="form" :rules="rules" ref="editForm" :inline="true">
        <el-form-item label="数据ID" :label-width="formLabelWidth" prop="monitorDataId">
          <el-input disabled v-model="form.monitorDataId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="监控数值" :label-width="formLabelWidth" prop="value">
          <el-input v-model="form.value" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="监控时间" :label-width="formLabelWidth" prop="monitorTime">
          <el-input disabled v-model="form.monitorTime" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
    <template slot="footer">
      <p align="right">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPageInfo.current" :page-sizes="pageSizeOptions" :page-size="currentPageInfo.size" layout="total, sizes, prev, pager, next, jumper" :total="currentPageInfo.total">
        </el-pagination>
      </p>
    </template>
  </d2-container>
</template>

<script>
import dayjs from 'dayjs'
import api from "@/api";
export default {
  data () {
    return {
      baseUrl: process.env.VUE_APP_API,
      uploadFileList: [],
      fileForm: {
        oriName: "",
        fileUuid: ""
      },
      culturePonds:[],
      searchForm: {
        culturePondId:'',
        dataType: 'WATER_TEMP',
        date: dayjs()
      },
      uploadDialogLoading:false,
      uploadDialogVisible:false,
      tableLoading: false,
      currentPageInfo: {
        current: 1,
        size: 10,
        total: 0
      },
      pageSizeOptions: [1, 5, 10, 20, 40],
      editLoading: false,
      formLabelWidth: "120px",
      form: {},
      tags: [],
      currentTag: null,
      dialogVisible: false,
      rules: {
        name: [
          { required: true, message: "请输入标签名称", trigger: "blur" },
          { min: 0, max: 32, message: "长度在 0 到 32 个字符", trigger: "blur" }
        ],
        timeRange: [
          { required: true, message: "请输入标签时间区间", trigger: "blur" }
        ],
        description: [
          {
            min: 0,
            max: 256,
            message: "长度在 0 到 256 个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    dialogTitle () {
      return this.currentTag == null
        ? "新增数据"
        : "编辑数据 - " + this.currentTag.monitorDataId;
    },
    isNew () {
      return this.currentTag == null;
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.uploadDialogLoading = true;
      if (res.code !== 200) {
          this.$message({
            message: res.message,
            type: "error"
          });
          this.uploadFileList = []
      }
          this.$message({
            message: '上传成功！',
            type: "success"
          });
          this.uploadDialogVisible = false
          this.uploadFileList = []
      this.uploadDialogLoading = false;
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传文件只能是EXCEL!');
        }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        return isJPG && isLt2M;
    },
    handleRemove (file, fileList) { },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    calTimeRangeDesc (row) {
      return dayjs('20200101' + row.startTime).format('HH:mm:ss') + '~' + dayjs('20200101' + row.endTime).format('HH:mm:ss')
    },
    handleSizeChange (val) {
      this.currentPageInfo.size = val;
      this.currentPageInfo.current = 1;
      this.tagList();
    },
    handleCurrentChange (val) {
      this.currentPageInfo.current = val;
      this.tagList();
    },
    showDialog (currentTag) {
      this.currentTag = JSON.parse(JSON.stringify(currentTag));
      this.form = JSON.parse(JSON.stringify(currentTag));
      this.dialogVisible = true;
    },
    deleteTag (tag) {
      this.$confirm('确定要删除"' + tag.monitorDataId + '"数据项吗？', "删除数据", {
        type: "warning"
      }).then(async _ => {
        var res = await api.service.delete("/monitorData", {
          params: {
            id: tag.monitorDataId
          }
        }).catch(function(error) { });
        if (res) {
          this.$message({
            message: "删除成功！",
            type: "success"
          });
          this.tagList();
        }
      });
    },
    submit () {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.editLoading = true;
          var res = await api.service.put("/monitorData?id=" + this.form.monitorDataId + '&value=' + this.form.value, {}).catch(function(error) { });
          if (res) {
            this.$message({
              message: this.isNew ? "新增成功！" : "修改成功！",
              type: "success"
            });
            this.dialogVisible = false;
            this.tagList();
          }
          this.editLoading = false;
        }
      });
    },
    async tagList () {
      this.tableLoading = true;
      var data = await api.service.get("/monitorData/page", {
        params: {
          pageSearchCount:true,
          name: this.searchForm.name,
          pageCurrent: this.currentPageInfo.current,
          pageSize: this.currentPageInfo.size,
          culturePondId: this.searchForm.culturePondId,
          date: dayjs(this.searchForm.date).format('YYYY-MM-DD'),
          dataType: this.searchForm.dataType
        }
      }).catch(function(error) { });
      this.currentPageInfo = data;
      this.tags = data.records;
      this.tableLoading = false;
    },
   async culturePondsQuery () {
      this.tableLoading = true;
      var data = await api.service.get("/culturePond");
      this.culturePonds = data;
      this.searchForm.culturePondId = data[0].id
    },
    uploadExcel () {
      this.$refs.upload.submit();
    }
  },
  async created () {
    await this.culturePondsQuery();
    this.tagList();
  }
};
</script>
